from threading import Thread
from time import sleep
#import hashlib
import socket
import os

# 依赖于数据的列表+写入的文件
def write_file():
    global list_file_data, file_get
    while True:
        if if_stop_get==True and list_file_data==[]:
            break
        # 在数据列表为空+不打扰在数据列表中加入数据+传输完成时：写入数据到文件
        if list_file_data!=[]:
            if len(list_file_data)>= 2 or if_stop_get==False:
                try:
                    file_get.write(list_file_data[0])
                    list_file_data.pop(0)
                except:
                    pass

def get_file_size():
    global file_size_total, file_get_name, get_file_size_print
    while if_stop_get==False:
        get_file_size_print = '{}{:-2}{}{}{}'.format('Get : ',int(os.path.getsize(file_get_name)/1000000),' / ',file_size_total/1000000,' MB')
        print(get_file_size_print,end='\r')
        sleep(1)

# 保证在传输结束后，端口可复用
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 取得本地IP地址
conn_trycount = 0
while conn_trycount<3:
    try:
        conn_trycount += 1
        conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        conn.connect(("223.5.5.5",53))
        ip = conn.getsockname()[0]
        print('This ip : ', ip)
        conn.close()

        ip_pre3 = ip.split('.')
        ip_4 = ip_pre3[3]
        ip_pre3[3] = ''
        ip_pre3 = '.'.join(ip_pre3)
        break
    except:
        conn_trycount += 1


# 支持(192.168.x.)x的两种输入格式
server = input('Get : from IP: (%s) ' %ip_pre3)
port = 1079
server = server.split('.')
if len(server) == 1:
    server = "%s%s" %(ip_pre3,server[0])
elif len(server) == 4:
    server = '.'.join(server)

print(server)
s.connect((server, port))

if_stop_get=False
t=Thread(target=write_file)
t2=Thread(target=get_file_size)

get = s.recv(131072)
if_create_file=False
list_file_data=[]
get_file_size_print=''
t.start()
while get:
    if if_create_file==False:
        get=get.split(b'0x00',3)
        try:
            os.remove(get[0])
        except:
            pass
        file_get_name = get[0].decode(encoding="utf-8")
        file_get = open(file_get_name, "ab+")
        if_create_file=True
        if get[1] == b'0x01':
            if_unzip = True
            print("Get : <dir> %s" %file_get_name.split('.zip',-1)[0])
        elif get[1] == b'0x02':
            if_unzip = False
            print("Get : %s" %file_get_name)
        file_size_total = int(get[2].decode(encoding="utf-8"))
        t2.start()
        list_file_data.append(get[3])
    #print(get)
    get = s.recv(131072)
    list_file_data.append(get)

s.close()
while list_file_data!=[]:
    sleep(0.5)
# write_file多线程函数将在声明if_stop_get=True + 数据列表为空后结束
# 用空格覆盖get_file_size多线程函数的print内容
print(''.ljust(len(get_file_size_print)),end='\r')
if_stop_get=True
file_get.close()

#print(hashlib.md5(open(f_name[0], "rb").read()).hexdigest())
print("Get : Done")

if if_unzip == True:
    import zipfile
    dir_name = os.getcwd() + '//' + file_get_name.split('.zip',-1)[0]
    print("Extract : <dir> %s" %file_get_name.split('.zip',-1)[0], end='\r')
    try:
        os.mkdir(dir_name)
    except:pass
    with zipfile.ZipFile(file_get_name,'r') as file_as_zip:
        file_as_zip.extractall(path=dir_name)
        file_as_zip.close()
    try:
        os.remove(file_get_name)
    except:
        pass
    print("File : Extracting : Done")



